#include <bits/stdc++.h>
// 2025/03/02
// tag: 
// Author: Forever
using namespace std;

using int64 = int64_t;

int t, n, m, cnt, vis[1001][1001];
char maze[1001][1001];
bool type[1001][1001];

void init(){
    memset(vis, 0, sizeof(vis));
    memset(type, 0, sizeof(type));
    cin >> n >> m;
    cnt = 0;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++) 
            cin >> maze[i][j];
}

bool dfs(int x, int y){
    if (x == n + 1 || y == m + 1 || x == 0 || y == 0)
        return type[x][y] = false;
    if (vis[x][y] == cnt || maze[x][y] == '?')
        return type[x][y] = true, vis[x][y] = cnt;
    if (vis[x][y])
        return type[x][y];
    vis[x][y] = cnt;
    if (maze[x][y] == 'U')
        return type[x][y] = dfs(x - 1, y);
    else if (maze[x][y] == 'D')
        return type[x][y] = dfs(x + 1, y);
    else if (maze[x][y] == 'L')
        return type[x][y] = dfs(x, y - 1);
    else 
        return type[x][y] = dfs(x, y + 1);
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> t;
    while (t--) {
        init();
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++)
                if (!vis[i][j])
                    cnt++, dfs(i, j);
        
        int c = 0;
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++)
                if ((type[i][j] && maze[i][j] != '?') || (type[i - 1][j] || type[i + 1][j] || type[i][j - 1] || type[i][j + 1]) && maze[i][j] == '?')
                    c++;
        cout << c << endl;
    }
    return 0;
}